<template>
  <BasicModal
    :title="t('layout.header.dropdownChangeTenant')"
    v-bind="$attrs"
    @register="register"
    @ok="handelSubmit"
    @cancel="handelCancel"
  >
    <BasicForm @register="registerForm">
      <template #tenant="{ model, field }">
        <RadioGroup v-model:value="model[field]">
          <Radio :style="radioStyle" :value="val.tenantId" v-for="(val, key) in tenants" :key="key"
            >{{ val.name }}</Radio
          >
        </RadioGroup>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { Radio } from 'ant-design-vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { ref } from 'vue';
  import { TENANT_KEY } from '@/enums/cacheEnum';
  import { setAuthCache, getTenant } from '@/utils/auth';

  const RadioGroup = Radio.Group;
  const { t } = useI18n();
  const [register, { closeModal }] = useModalInner(async () => {
    initData();
  });

  const tenants = ref([
    {
      tenantId: '11111',
      name: '租户1',
    },
    {
      tenantId: '22222',
      name: '租户2',
    },
    {
      tenantId: '33333',
      name: '租户3',
    }
  ]);
  const radioStyle = ref({
    display: 'flex',
    height: '30px',
    lineHeight: '30px',
  });
  const [registerForm, { validateFields, setFieldsValue }] = useForm({
    showActionButtonGroup: false,
    schemas: [
      {
        field: 'tenant',
        label: t('layout.header.dropdownChangeTenant'),
        colProps: {
          span: 24,
        },
        defaultValue: '',
        required: true,
        // component: 'Input',
        slot: 'tenant',
      },
    ],
  });
  const handelSubmit = async () => {
    const values = await validateFields();
    setAuthCache(TENANT_KEY, values.tenant);
    location.reload();
  };
  const handelCancel = () => {
    closeModal();
  };
  const initData = () => {
    const key = getTenant()
    if (key) {
      setFieldsValue({
        tenant: key,
      });
    }
  };
</script>
